package com.ala4.oxcafe.common.utils;

import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * ResponseWriter 注意，调用 ResponseWriter 后，不应该再执行其它方法，response 已经关闭.
 *
 * @author PING
 * @version 1.0
 * @date 2024/12/20 12:42
 */
@Slf4j
public class ResponseWriter {

    private ResponseWriter() {
    }

    public static void write(HttpServletResponse response, Object value) {
        setWriteJsonResponse(response);
        try {
            response.getWriter().write(JSONUtil.toJsonStr(value));
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        }
    }

    private static void setWriteJsonResponse(HttpServletResponse response) {
        response.setStatus(HttpStatus.OK.value());
        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
        response.setCharacterEncoding(StandardCharsets.UTF_8.displayName());
    }
}